//
//  TableViewController.swift
//  classWork4_5repeat
//
//  Created by Qingke on 16/4/8.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

class TableViewController: UITableViewController {
    var imgs = [cellClass]()
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = editButtonItem()  //这里只是为了演示用代码创建 navigationItem.leftBarButtonItem的方法，不需要用subview方法 很特别，但是我不喜欢用这样代码实现，不直观，对于其它人来说
        navigationItem.leftBarButtonItem?.title = "编辑"
        
        if let date = loadDate() {
            imgs += date
        }
        
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
    
    @IBAction func unWindForSegueList (segue: UIStoryboardSegue) {
        if let senderViewController = segue.sourceViewController as? ViewController ,
            img = senderViewController.imgOfTheView {
               //通过if let 判断对像， 来区分对象。 用来实现保存 还是  编辑修改
                if let selectedCellPath = tableView.indexPathForSelectedRow {
                    imgs[selectedCellPath.row] = img  //刷新数据
                    tableView.reloadRowsAtIndexPaths([ selectedCellPath], withRowAnimation: .Fade)
                } else {
                    //添加Cell
                    let newInsertCellPath = NSIndexPath(forRow: imgs.count, inSection: 0) // inSection = 1 错误 修改后可行，这由于Tabel中只有一个section 从零开始，修改 2个 section 可行, 但会导致重复内容多次显示，因为cell是全对象的，需要分开处理等。
                    imgs.append(img) //这里添加是数据的一致性需要，表示在数据组中加入一个对象
                    tableView.insertRowsAtIndexPaths([newInsertCellPath], withRowAnimation: .Automatic)
                }
                saveDate()
        }
    }
    
    func showWorring() {
        let alertController = UIAlertController(title: "删完啦", message: "你不能再删除了", preferredStyle: .Alert)
        let alertAction = UIAlertAction(title: "确定", style: .Default) { (action) -> Void in
            print("点了确定")
        }
        alertController.addAction(alertAction)
        presentViewController(alertController, animated: true, completion: nil)
    }
    
    
    func saveDate(){
        let isSaveSuccess = NSKeyedArchiver.archiveRootObject( imgs, toFile: cellClass.ArchiveURl.path!)
        if !isSaveSuccess {
            print("保存失败")
        } else {
            print("保存成功")
        }
    }
    
    func loadDate() ->[cellClass]? {
        return NSKeyedUnarchiver.unarchiveObjectWithFile(cellClass.ArchiveURl.path!) as? [cellClass]
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 2
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if section == 0 {
            return imgs.count
        } else {
            return 2
        }
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCellWithIdentifier("ShowTableCell", forIndexPath: indexPath) as! TableViewCell // " "中的内容是cell的Id
            let iM = imgs[indexPath.row]
            
            cell.imgViewOfCell.image = iM.photo
            cell.nameLabelOfCell.text = iM.name
            cell.starNum.rating = iM.starNum
            return cell
        } else {
           return UITableViewCell()
        }
    }
    

  
    
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }


    
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            //数据一致需要删除，列表中的一个indexpath.row
            if imgs.isEmpty {
                showWorring() //待实现
            }
            imgs.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
            if segue.identifier == "edit" {
                let  showViewController = segue.destinationViewController as! ViewController
                let selectCell = sender as! TableViewCell
                let selectCell_indexPath = tableView.indexPathForCell( selectCell )
                let selectCell_content = imgs[selectCell_indexPath!.row]
                showViewController.imgOfTheView = selectCell_content
            } else {
                print("add")
                
            }
        
        
        }

}
